import axios from 'axios'
import { Message } from 'element-ui'
import { getToken } from '@/utils/auth'
import store from '@/store'
// 引入路由
import router from '@/router'

// 1-创建路由实例
const instance = axios.create({
  baseURL: 'http://hmmm-api.itheima.net/',
  timeout: 5000 // request timeout
})

// 2-请求拦截器，统一注入token
instance.interceptors.request.use(
  config => {
    // Do something before request is sent
    const token = store.getters.token
    if (token) {
      config.headers.Authorization = `Bearer ${getToken()}`
    }
    return config
  },
  error => {
    // Do something with request error
    // console.log(error) // for debug
    return Promise.reject(error)
  }
)

// 3-响应拦截器，处理数据异常
instance.interceptors.response.use(
  response => {
    // console.log(response)
    if (response.status === 200) {
      return response
    } else {
      return Promise.reject(response)
    }
  },
  error => {
    // console.dir(error) // 打印错误对象
    if (error && error.response && error.response.status === 401) {
      // 调登出接口
      store.dispatch('FedLogOut')
      // 错误提示
      Message({
        message: error.message,
        type: 'error',
        duration: 5 * 1000
      })
      // 跳转至登录页
      return router.push('/login')
    }
    return Promise.reject(error)
  }
)

export const createAPI = (url, method, data) => {
  const config = {}
  if (method === 'get') {
    config.params = data
  } else {
    config.data = data
  }
  return instance({
    url,
    method,
    ...config
  })
}

export const createFormAPI = (url, method, data) => {
  const config = {}
  config.data = data
  config.headers = {
    'Cache-Control': 'no-cache',
    'Content-Type': 'application/x-www-form-urlencoded'
  }
  config.responseType = 'json'
  config.transformRequest = [
    function (data) {
      let ret = ''
      for (const it in data) {
        ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
      }
      return ret
    }
  ]
  return instance({
    url,
    method,
    ...config
  })
}
// 4-导出路由实例
export default instance
